package controller;

import model.City;
import model.Country;

import java.sql.SQLException;
import java.util.ArrayList;

import db.DBCity;
import db.DBConnection;
import db.IFCity;

public class CityController {
	
	private static CityController instance = null;
	
	public static CityController getInstance()
	{
		if(instance == null)
			instance = new CityController();
		
		return instance;
	}
	
	public CityController()
	{
		
	}
	
	public int addNewCity(String name, Country country )
	{
		int result = -2;
		try
		{
			City city = new City();
			city.setCountry(country);
			city.setName(name);
			DBConnection.startTransaction();
			IFCity dbCity = new DBCity();
			result = dbCity.createCity(city);
			DBConnection.commitTransaction();
		} // end of try
		catch (Exception e)
		{
			if(DBConnection.doDebug())
			{
			System.out.println("Could not add new City, error : " + e);
			DBConnection.rollbackTransaction();
			} // end of if
		} // end of catch
		
		return result;
	}
	
	public int updateCity(int cityID, String name, Country country)
	{
		int result = -2;
		try
		{
			City city = new City();
			city.setCountry(country);
			city.setName(name);
			city.setCityID(cityID);
			DBConnection.startTransaction();
			IFCity dbCity = new DBCity();
			result = dbCity.updateCity(city);
			DBConnection.commitTransaction();
		} // end of try
		catch (Exception e)
		{
			if(DBConnection.doDebug())
			{
			System.out.println("Could not update City, error : " + e);
			DBConnection.rollbackTransaction();
			} // end of if
		} // end of catch
		
		return result;
	}
	
	public ArrayList<City> getCitiesByAllInfo(String search) throws SQLException
	{
		IFCity dbCity = new DBCity();
		return dbCity.getCitiesByAllInfo(search);
	}
	
	public ArrayList<City> getCitiesByCountryName(String name) throws SQLException
	{
		IFCity dbCity = new DBCity();
		return dbCity.getCitiesByCountryName(name);
	}
	
	public ArrayList<City>  getCityByName(String name) throws SQLException
	{
		IFCity dbCity = new DBCity();
		return dbCity.getCityByName(name);
	}
	
	public City getOneCity(String column, String value, String name)throws SQLException
		{
			IFCity dbCity = new DBCity();
			return dbCity.getOneCity(column, value, name);
		}
	
	public ArrayList<City> getAllCities() throws SQLException
	{
		IFCity dbCity = new DBCity();
		return dbCity.getAllCities();
	}

}
